/*
 * CageballServerView.java
 */
package cageballserverapp;

import cageballcommon.exceptions.CageballIOException;
import cageballcommon.exceptions.CageballMatchException;
import cageballserver.CageballClient;
import cageballserver.CageballNotifier;
import cageballserver.CageballServer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.Task;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;

/**
 * The application's main frame.
 */
public class CageballServerView extends FrameView implements CageballNotifier {

    private CageballServer server;
    Properties serverProperties = new Properties();

    public CageballServerView(SingleFrameApplication app) {
        super(app);

        try {

            Properties gameProperties = new Properties();
            Properties physicsProperties = new Properties();

            serverProperties.load(new FileInputStream("server.properties"));
            gameProperties.load(new FileInputStream("game.properties"));
            physicsProperties.load(new FileInputStream("physics.properties"));

            server = new CageballServer(serverProperties, gameProperties, physicsProperties, this);
        } catch (Exception ex) {
            print("Error loading config files");
            print(ex.getMessage());
        }
        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = CageballServerApp.getApplication().getMainFrame();
            aboutBox = new CageballServerAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        CageballServerApp.getApplication().show(aboutBox);
    }

    private boolean validMatchSelection() {
        Object[] selected = jList1.getSelectedValues();

        return (selected.length >= 2);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        jMenuServer = new javax.swing.JMenu();
        jMenuItemStart = new javax.swing.JMenuItem();
        jMenuItemStop = new javax.swing.JMenuItem();
        jMenuItemRestart = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        jMenuItemRefresh = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        jButton1 = new javax.swing.JButton();

        mainPanel.setName("mainPanel"); // NOI18N

        jSplitPane1.setBorder(null);
        jSplitPane1.setName("jSplitPane1"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jTextArea1.setName("jTextArea1"); // NOI18N
        jScrollPane2.setViewportView(jTextArea1);

        jSplitPane1.setRightComponent(jScrollPane2);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jList1.setName("jList1"); // NOI18N
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        jSplitPane1.setLeftComponent(jScrollPane1);

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE)
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(cageballserverapp.CageballServerApp.class).getContext().getResourceMap(CageballServerView.class);
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(cageballserverapp.CageballServerApp.class).getContext().getActionMap(CageballServerView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        jMenuServer.setAction(actionMap.get("refresh")); // NOI18N
        jMenuServer.setText(resourceMap.getString("jMenuServer.text")); // NOI18N
        jMenuServer.setName("jMenuServer"); // NOI18N

        jMenuItemStart.setAction(actionMap.get("startServer")); // NOI18N
        jMenuItemStart.setText(resourceMap.getString("jMenuItemStart.text")); // NOI18N
        jMenuItemStart.setName("jMenuItemStart"); // NOI18N
        jMenuServer.add(jMenuItemStart);

        jMenuItemStop.setAction(actionMap.get("stopServer")); // NOI18N
        jMenuItemStop.setText(resourceMap.getString("jMenuItemStop.text")); // NOI18N
        jMenuItemStop.setName("jMenuItemStop"); // NOI18N
        jMenuServer.add(jMenuItemStop);

        jMenuItemRestart.setAction(actionMap.get("restartServer")); // NOI18N
        jMenuItemRestart.setText(resourceMap.getString("jMenuItemRestart.text")); // NOI18N
        jMenuItemRestart.setName("jMenuItemRestart"); // NOI18N
        jMenuServer.add(jMenuItemRestart);

        jSeparator1.setName("jSeparator1"); // NOI18N
        jMenuServer.add(jSeparator1);

        jMenuItemRefresh.setAction(actionMap.get("refresh")); // NOI18N
        jMenuItemRefresh.setText(resourceMap.getString("jMenuItemRefresh.text")); // NOI18N
        jMenuItemRefresh.setName("jMenuItemRefresh"); // NOI18N
        jMenuServer.add(jMenuItemRefresh);

        menuBar.add(jMenuServer);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        jButton1.setAction(actionMap.get("playMatch")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(statusPanelLayout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE))
                    .addGroup(statusPanelLayout.createSequentialGroup()
                        .addComponent(statusMessageLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 390, Short.MAX_VALUE)
                        .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(statusAnimationLabel)
                        .addContainerGap())))
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton1)
                    .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged

        if (validMatchSelection()) {
            jButton1.setEnabled(true);
        } else {
            jButton1.setEnabled(false);
        }
    }//GEN-LAST:event_jList1ValueChanged

    @Action
    public Task startServer() {
        return new StartServerTask(getApplication());
    }

    public void clientConnected(CageballClient client) {
        refresh();
    }

    public void clientDisconnected(CageballClient client) {
        refresh();
    }

    public void clientUpdated(CageballClient client) {
        refresh();
    }

    public void message(String message) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    private class StartServerTask extends org.jdesktop.application.Task<Object, Void> {

        StartServerTask(org.jdesktop.application.Application app) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to StartServerTask fields, here.
            super(app);
        }

        @Override
        protected Object doInBackground() {
            try {
                print("Starting the server...");
                server.startServer();
            } catch (CageballIOException ex) {
                return ex.getMessage();
            }
            return null;  // return your result
        }

        @Override
        protected void succeeded(Object result) {
            if (result == null) {
                print("Match server running on port " + serverProperties.getProperty("gamePort"));
                print("Observer server running on port " + serverProperties.getProperty("observerPort"));
            } else {
                print((String) result);
            }
            updateServerButtons();
        }
    }

    @Action
    public Task stopServer() {
        return new StopServerTask(getApplication());
    }

    private class StopServerTask extends org.jdesktop.application.Task<Object, Void> {

        StopServerTask(org.jdesktop.application.Application app) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to StopServerTask fields, here.
            super(app);
        }

        @Override
        protected Object doInBackground() {
            try {
                print("Stopping the server...");
                server.stopServer();
            } catch (CageballIOException ex) {
                return ex.getMessage();
            }
            return null;  // return your result
        }

        @Override
        protected void succeeded(Object result) {
            refresh();
            if (result == null) {
                print("Server stopped");
            } else {
                print((String) result);
            }
            updateServerButtons();
            refresh();
        }
    }

    @Action
    public Task restartServer() {
        return new RestartServerTask(getApplication());
    }

    private class RestartServerTask extends org.jdesktop.application.Task<Object, Void> {

        RestartServerTask(org.jdesktop.application.Application app) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to RestartServerTask fields, here.
            super(app);
        }

        @Override
        protected Object doInBackground() {
            try {
                print("Restarting the server...");
                server.stopServer();
                server.startServer();
            } catch (CageballIOException ex) {
                return ex.getMessage();
            }
            return null;  // return your result
        }

        @Override
        protected void succeeded(Object result) {
            if (result == null) {
                print("Server restarted");
                print("Match server running on port " + serverProperties.getProperty("gamePort"));
                print("Observer server running on port " + serverProperties.getProperty("observerPort"));
            } else {
                print((String) result);
            }
            updateServerButtons();
            refresh();
        }
    }

    @Action
    public void refresh() {
        Collection<CageballClient> clients = server.getClients();
        if (clients != null) {
            jList1.setListData(clients.toArray());
        }
    }

    @Action
    public void playMatch() {
        Object[] selected = jList1.getSelectedValues();
        List<cageballserver.CageballClient> list = new ArrayList<cageballserver.CageballClient>();

        for (int i = 0; i < selected.length; i++) {
            list.add((CageballClient)selected[i]);
        }

        try {

            print("Starting game with: ");

            for (CageballClient c : list) {
                print(c.getInitTeam().getTeamName());
            }
            print("\n");

            server.addMatch(list);
            refresh();

        } catch (CageballIOException ex) {
            Logger.getLogger(CageballServerView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CageballMatchException ex) {
            print(ex.getMessage());
        }

    }

    private void print(String message) {
        jTextArea1.append(message + "\n");
    }

    private void updateServerButtons() {

        boolean value = server.isRunning();

        jMenuItemStart.setEnabled(!value);
        jMenuItemStop.setEnabled(value);
        jMenuItemRestart.setEnabled(value);
        jMenuItemRefresh.setEnabled(value);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JList jList1;
    private javax.swing.JMenuItem jMenuItemRefresh;
    private javax.swing.JMenuItem jMenuItemRestart;
    private javax.swing.JMenuItem jMenuItemStart;
    private javax.swing.JMenuItem jMenuItemStop;
    private javax.swing.JMenu jMenuServer;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
}
